package com.lemon.smartsafety.update;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class UpdateManager {
    private LoggerHelper loggerHelper = new LoggerHelper(UpdateManager.class);

    private static final String TAG = "UpdateManager";
    // 提示语
    private String updateMsg;

    // 返回的安装包url
    private String apkUrl;


    /* 下载包安装路径 */
    private String savePath;
    private String fileName = Constants.APP_DOWNLOAD_FILE_NAME;
    private String mVersionName = "1.0";
    private Activity activity;
    private boolean mForceUpdate = false;

    private String saveFileName = savePath + fileName;

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    private TextView txtProgress;

    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;
    private static final int DOWN_ERROR = 3;

    private int progress;
    private String proText;

    private Thread downLoadThread;

    private boolean interceptFlag = false;
    /* 控制是否已经进行下载了 */
    private boolean isGoDownloading = false;

    private MaterialDialog.Builder mMaterialDialog;

    private MaterialDialog downloadDialog;

    /**
     * 处理进度界面用
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    txtProgress.setText(proText);
                    break;
                case DOWN_OVER:
                    haveDownLoad();
                    break;
                case DOWN_ERROR:
                    if (downloadDialog != null) {
                        downloadDialog.dismiss();
                    }
                    Toast.makeText(activity, "下载失败", Toast.LENGTH_SHORT).show();
                default:
                    break;
            }
        }
    };

    // cancel progressBar and start new App
    protected void haveDownLoad() {
        mHandler.post(new Runnable() {
            public void run() {
                mMaterialDialog = getMaterialDialog(activity, "安装更新", "是否安装更新？", "确定", "取消", new DialogClickMethod() {
                    @Override
                    public void positiveClick() {
                        installApk();
                        AppManager.getAppManager().AppExit();
                    }

                    @Override
                    public void negativeClick() {
                    }
                });
                mMaterialDialog.show();
            }
        });
    }


    public UpdateManager(Activity activity) {
        this.activity = activity;
    }
//
//    /**
//     * 实例化更新类
//     *
//     * @param updateMsg 更新内容
//     * @param apkUrl    更新文件Web地址
//     * @param activity  调用的Activity
//     */
//    public UpdateManager(String updateMsg, String apkUrl, String versionName, String fileName, Activity activity) {
//        super();
//        this.updateMsg = updateMsg;
//        this.apkUrl = apkUrl;
//        this.fileName = fileName;
//        this.activity = activity;
//        this.mVersionName = versionName;
//
//    }

    public UpdateManager(String updateMsg, String apkUrl, String versionName, String fileName, boolean forceUpdate, Activity activity) {
        super();
        this.updateMsg = updateMsg;
        this.apkUrl = apkUrl;
        this.fileName = fileName;
        this.activity = activity;
        this.mVersionName = versionName;
//        this.mForceUpdate = false;
        this.mForceUpdate = forceUpdate;
    }

    /**
     * 初始化后执行的方法（外部接口让主Activity调用）
     */
    public void checkUpdateInfo() {
        this.savePath = FileUtil.getAppFilesDir(activity);
        if (this.savePath == null || this.savePath.length() == 0) {
            Toast.makeText(activity, "获取缓存目录失败", Toast.LENGTH_SHORT).show();
            return;
        }
        saveFileName = this.savePath + File.separator + this.fileName;
        showNoticeDialog();
    }

    private void showNoticeDialog() {

        mMaterialDialog = new MaterialDialog.Builder(activity).title("发现新版本（" + this.mVersionName + "）");


        if (mForceUpdate) {
            final LayoutInflater inflater = LayoutInflater.from(activity);
            View v = inflater.inflate(R.layout.view_dialog_update_content, null);
            TextView tvSubTitle = (TextView) v.findViewById(R.id.id_tv_subtitle);
            tvSubTitle.setText("必须更新！");

            TextView tvContent = (TextView) v.findViewById(R.id.id_tv_content);
            tvContent.setText(Html.fromHtml(updateMsg));
            mMaterialDialog.canceledOnTouchOutside(false);
            mMaterialDialog.customView(v, false);
            mMaterialDialog.dismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!BuildConfig.DEBUG && !isGoDownloading) {
                        AppManager.getAppManager().AppExit();
                    }
                }
            });

            mMaterialDialog.positiveText("下载");
            mMaterialDialog.onAny(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        isGoDownloading = true;
                        showDownloadDialog();
                    }
                }
            });
        } else {
            mMaterialDialog.positiveText("下载");
            mMaterialDialog.negativeText("取消");
            mMaterialDialog.canceledOnTouchOutside(true);
            mMaterialDialog.dismissListener(null);
            mMaterialDialog.onAny(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        showDownloadDialog();
                    }
                }
            });
            mMaterialDialog.content(Html.fromHtml(updateMsg));
        }
        mMaterialDialog.cancelable(false);
        downloadDialog = mMaterialDialog.show();
    }

    /**
     * 显示下载对话框
     */
    private void showDownloadDialog() {
        mMaterialDialog = new MaterialDialog.Builder(activity).title("软件版本更新");
        mMaterialDialog.canceledOnTouchOutside(false);
        mMaterialDialog.cancelable(false);
        final LayoutInflater inflater = LayoutInflater.from(activity);
        View v = inflater.inflate(R.layout.update_progress_dialog, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
        txtProgress = (TextView) v.findViewById(R.id.progress_status);
        mMaterialDialog.customView(v, false);

        mMaterialDialog.positiveText("取消");
        mMaterialDialog.onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                interceptFlag = true;
                if (mForceUpdate) {
                    AppManager.getAppManager().AppExit();
                }
                if (BuildConfig.DEBUG) {
                    loggerHelper.i("cancel download");
                }
            }
        });
        mMaterialDialog.show();
        downloadApk();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                conn.setReadTimeout(30);
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                File ApkFile = new File(saveFileName);
                if (!ApkFile.exists()) {
                    ApkFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    proText = (int) (((float) count / length) * 100) + "/100%";
                    // 更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        if (downloadDialog != null) {
                            downloadDialog.dismiss();
                        }
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 点击取消就停止下载.
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                if (interceptFlag) {
                    return;
                }
                mHandler.sendEmptyMessage(DOWN_ERROR);
            } catch (IOException e) {
                e.printStackTrace();
                if (interceptFlag) {
                    return;
                }
                mHandler.sendEmptyMessage(DOWN_ERROR);
            }

        }
    };

    /**
     * 下载apk
     */

    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        activity.startActivity(i);

    }


    private MaterialDialog.Builder getMaterialDialog(Context context,String title, String msg, String positiveMsg, String negativeMsg, final DialogClickMethod clickMethod) {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(context).title(title).content(msg).positiveText(positiveMsg).negativeText(negativeMsg).onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    clickMethod.positiveClick();
                } else if (which == DialogAction.NEGATIVE) {
                    clickMethod.negativeClick();
                }
            }
        });
        return builder;
    }

    public interface DialogClickMethod {
        public void positiveClick();
        public void negativeClick();
    }

}
